package cn.tedu.kcircle.common.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.*;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    public static synchronized String generate(Map<String, Object> claims, String secretKey) {
        JwtBuilder builder = Jwts.builder();
        builder.header().add("alg", "HS256").add("typ", "JWT");
        builder.claims().add(claims);
        byte[] keyBytes = Decoders.BASE64.decode(secretKey);
        Key key = Keys.hmacShaKeyFor(keyBytes);
        builder.signWith(key,(SecureDigestAlgorithm) Jwts.SIG.HS256);
        return builder.compact();
    }

    /**
     * 解析JWT
     *
     * @param jwt       JWT数据
     * @param secretKey 生成JWT时使用的密钥
     * @return 解析结果
     */
    public static synchronized Claims parse(String jwt, String secretKey) {
        JwtParserBuilder parser = Jwts.parser();
        byte[] bytes = Decoders.BASE64.decode(secretKey);
        SecretKey key = Keys.hmacShaKeyFor(bytes);
        parser.verifyWith(key);
        return parser.build().parseSignedClaims(jwt).getPayload();
    }

    public static void main(String[] args) {
        String secretKey="d8hf8939938g89938g89938g89938g89938g8rjdfvnijiwdwe";
        HashMap claims = new HashMap<>();
        claims.put("id",1);
        claims.put("name","zs");
        String jwt = generate(claims, secretKey);
        System.out.println(jwt);
        Claims parse = parse(jwt, secretKey);
        System.out.println(parse);
    }
}
